package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.dto.ProductDetailRequest;
import com.cskaoyan.mall.dto.ProductDetailResponse;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.order.api.ProductFeignClient;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * OrderCoreServiceImpl
 *
 * @param
 * @return
 * @2022/4/22
 **/
@Service
public class OrderCoreServiceImpl implements OrderCoreService {
    @Autowired
    OrderConverter orderConverter;

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    ProductFeignClient productFeignClient;
    /**
     * 创建订单
     * @param request
     * @return
     */
    @Override
    @Transactional
    public CreateOrderResponse createOrder(CreateOrderRequest request) {

        CreateOrderContext createOrderContext = new CreateOrderContext();



        CreateOrderResponse response=new CreateOrderResponse();
        try {
            request.requestCheck();
//order
            Order order = new Order();
            order.setUpdateTime(new Date());
            order.setCreateTime(new Date());
            order.setStatus(0);
            GlobalIdGeneratorUtil globalIdGeneratorUtil = new GlobalIdGeneratorUtil();
            String order_id = globalIdGeneratorUtil.getNextSeq("order_id", 1);
//      TODO
            order.setOrderId(order_id);
            order.setUserId(request.getUserId());
            order.setPayment(request.getOrderTotal());
            orderMapper.insertSelective(order);
//
            List<CartProductDto> goods = request.getCartProductDtoList();
            for (CartProductDto good : goods) {
                OrderItem orderItem = new OrderItem();
//      TODO          orderItem.setId();
                String order_item_id = globalIdGeneratorUtil.getNextSeq("order_item_id", 1);
                orderItem.setId(order_item_id);
                orderItem.setItemId(good.getProductId());
                orderItem.setNum(Integer.parseInt(good.getProductNum() + ""));
//      TODO          orderItem.setOrderId( );
                orderItem.setOrderId(order_id);
                orderItem.setTitle(good.getProductName());
                orderItem.setPrice(good.getSalePrice());
//                double price = Double.parseDouble(good.getSalePrice() + "");
//                Double totalfee=good.getProductNum()*price ;
//                orderItem.setTotalFee(totalfee);
                orderItem.setPicPath(good.getProductImg());
                orderItem.setStatus(0);

                orderItem.setCreateTime(new Date());
                orderItem.setUpdateTime(new Date());
                orderItemMapper.insertSelective(orderItem);
//                orderItem.set
            }
//ordershopping---wuliu
            OrderShipping orderShipping = new OrderShipping();
            orderShipping.setOrderId(order.getOrderId());
            orderShipping.setReceiverName(request.getUserName());
            orderShipping.setReceiverPhone(request.getTel());
            orderShipping.setReceiverAddress(request.getStreetName());
            orderShipping.setCreated(new Date());
            orderShippingMapper.insertSelective(orderShipping);

            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
//            addressId -goods

//            response.setOrderId();
        } catch (ValidateException e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(OrderRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }
    /**
     * 取消订单
     * @param request
     * @return
     */
    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {

        CancelOrderResponse response=new CancelOrderResponse();
        try {
            request.requestCheck();
//            status=7
            System.out.println("request = " + request);
//            request = CancelOrderRequest(orderId={"id":"19081913521928018"})
            String[] split = request.getOrderId().split(":");
            String orderId =null;
            if (split.length > 1) {
                orderId = split[1].replace("}", "").trim();
                orderId=orderId.substring(1,orderId.length()-1);
            } else {
                throw   new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
            }
            System.out.println("orderId = " + orderId+",before get order");



            Example example=new Example(Order.class);
            example.createCriteria()
                    .andEqualTo("orderId",orderId);

//            .andEqualTo("status",0);
//            Order order = orderMapper.selectOneOrder(orderId);
            List<Order> orders = orderMapper.selectByExample(example);
            if (orders.size() < 1) {
                throw   new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());

            }
            Order order = orders.get(0);
            System.out.println("order = " + order);
            if (order == null) {
                throw   new BizException(OrderRetCode.DB_EXCEPTION.getCode(),OrderRetCode.DB_EXCEPTION.getMessage());
            }
            order.setStatus(7);
            order.setUpdateTime(new Date());
            orderMapper.updateByPrimaryKey(order);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());

        }
        return response;
    }
    /**
     * 删除订单
     * @param request
     * @return
     */
    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        DeleteOrderResponse response=new DeleteOrderResponse();
        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            System.out.println("orderId = " + orderId);
            Order order = orderMapper.selectByPrimaryKey(orderId);
            System.out.println("order = " + order);
            int i = orderMapper.deleteByPrimaryKey(order);
            if (i < 1) {
                throw  new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
                        OrderRetCode.DB_EXCEPTION.getMessage());
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        }  catch (Exception e) {
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }
    /**
     * 修改订单状态
     * 状态 0未付款 1已付款 4交易成功 5交易关闭 6交易失败 7-已退款
     * 2未发货 3已发货
     * @param status
     * @param orderId
     */
    @Override
    public void updateOrder(Integer status, String orderId) {
//        orderId(example)-orderitemId(order_id)-orderitemids1-stcokId1

        if (status == null || "".equals(orderId)) {
            throw new ValidateException(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode(),OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
        }
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(status);
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKey(order);
//        if (OrderConstants.ORDER_STATUS_INIT==status) {
//            //初始化状态
////           nothing to do!!!
//        } else if (OrderConstants.ORDER_STATUS_PAYED == status) {
////           已支付
//
//
//        } else if (OrderConstants.ORDER_STATUS_TRANSACTION_SUCCESS == status) {
//
//        } else if (OrderConstants.ORDER_STATUS_TRANSACTION_FAILED == status) {
//
//        }


//        Example example = new Example(Order.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("order_id",orderId)
//                .andEqualTo("status",status-1);//0未付款->1已付款
//
//        List<Order> orders = orderMapper.selectByExample(example);
//        for (Order order : orders) {
//            order.setStatus(status);
//            order.setUpdateTime(new Date());
//            orderMapper.updateByPrimaryKey(order);
//            Example example2 = new Example(OrderItem.class);
//            Example.Criteria criteria2 = example.createCriteria();
//            criteria2.andEqualTo("order_id",orderId);
//
//            List<OrderItem> orderItems = orderItemMapper.selectByExample(example2);
//            for (OrderItem orderItem : orderItems) {
//                orderItem.
//            }
//        }
//
//
//        Order order = orderMapper.selectByPrimaryKey(orderId);
//        order.setStatus(status);
//        order.setUpdateTime(new Date());
//        orderMapper.updateByPrimaryKey(order);
////        TODO status and stock
//        if (status == 0) {
////            stock!
//            stockMapper.selectByPrimaryKey(orderId)
//            stockMapper.updateByPrimaryKey(stock);
//        }

    }

    @Override
    @Transactional
    public void deleteOrderWithTransaction(DeleteOrderRequest request) {
        request.requestCheck();
        String orderId = request.getOrderId();
        orderMapper.deleteByPrimaryKey(orderId);

    }

    /**
     *  支付成功时，更新订单状态，更新锁定库存，更新订单商品库存状态
     * @param request
     * @return
     */
    @Override
//    @Transactional
    public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {


        PayOrderSuccessResponse response=new PayOrderSuccessResponse();
        try {
            request.requestCheck();
            String orderId = request.getOrderId();

//            更新订单状态
//            Order order = orderMapper.selectByPrimaryKey(orderId);
//            order.setUpdateTime(new Date());//updateTime
//            order.setStatus(1);//status
//            orderMapper.updateByPrimaryKey(order);
            updateOrder(1,orderId);

//            1.order->item ids
            Example example = new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("order_id",orderId)
                    .andEqualTo("status","1");//1库存已锁定
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                orderItem.setStatus(3);//2库存已释放3-库存减扣成功'
                Integer num = orderItem.getNum();
                String id = orderItem.getId();
                //2.order- item
//                1已付款

                orderItemMapper.updateByPrimaryKeySelective(orderItem);
//                 更新订单商品库存状态更新锁定库存
//                2.stock
                Stock stock = stockMapper.selectStock(Long.parseLong(id));
                stock.setLockCount(0);
                stock.setStockCount(stock.getStockCount()-num);
                stockMapper.updateStock(stock);
            }
//
//
//
//
//            }
//
//            response.setCode(OrderRetCode.SUCCESS.getCode());
//            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (ValidateException e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode());
            response.setMsg(OrderRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
        } catch (Exception e) {
            response.setCode(OrderRetCode.INIT_ORDER_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }
        return response;
    }
}
